import Vue from 'vue'
import Vuex from 'vuex'
import getters from '@/store/getters.js'
import {
	USERINFO_CACHE_NAME,
	TOKEN_KEY,
	CATEGORY_LIST_KEY,
	CONTENT_HEIGHT,
	STATUS_HEIGHT_KEY,
	SEARCH_HISTORY_KEY,
	BANNER_IMAGE_KEY
} from '@/constant/index.js'
import request from '@/utils/request.js'
import { toast } from '@/utils/tool.js'
import location from '@/store/location.js'

Vue.use(Vuex)

function getSearchTag() {
	const value = uni.getStorageSync(SEARCH_HISTORY_KEY)
	if (!value || !Array.isArray(value)) return []
	return value
}

const store = new Vuex.Store({
	state: () => ({
		searchList: uni.getStorageSync('search_list') || [],
		userInfo: uni.getStorageSync(USERINFO_CACHE_NAME) || {},
		token: uni.getStorageSync(TOKEN_KEY) || '',
		categoryList: uni.getStorageSync(CATEGORY_LIST_KEY) || [],
		contentHeight: uni.getStorageSync(CONTENT_HEIGHT) || 500,
		statusBarHeight: uni.getStorageSync(STATUS_HEIGHT_KEY) || 0,
		orderData: uni.getStorageSync('order_data') || {},
		loginSuccess: false,
		hasLocation: false,
		historySearch: getSearchTag(),
		bannerImage: uni.getStorageSync(BANNER_IMAGE_KEY) || [],
	}),
	actions: {
		async initBanner({ commit }) {
			const resp = await request({
				url: "/index/getBanner",
			})
			if (!resp.data) resp.data = []
			commit('setBanner', resp.data.map(item => {
				const { article_id, banner_image } = item
				return { id: article_id, image: banner_image }
			}))
		},
		init({ commit, dispatch }) {
			commit('updateStatusHeight')
			dispatch('initBanner')
		},
		async getCategoryList({ commit }) {
			const resp = await request({
				url: '/article/cate',
			})
			const { code, data } = resp
			if (code !== 1) return
			commit('setCategory', data)
		},
		getUserinfo({ commit }) {
			return new Promise(async resolve => {
				const resp = await request({
					url: '/user/center',
				})
				const { code, data } = resp
				if (code !== 1) {
					commit('logout')
					toast({ title: '请完成登录' }, () => {
						uni.redirectTo({
							url: '/pages/login/login'
						})
					})
					return resolve([true, null])
				}
				commit('setUserInfo', data)
				resolve([null, data])
			})
		},
		logout({ commit }) {
			return new Promise(async resolve => {
				const resp = await request({
					url: '/login/logout',
				})
				const { code, msg } = resp
				if (code !== 1) {
					resolve(false)
					return toast({ title: msg })
				}
				commit('logout')
				return resolve(true)
			})
		},
	},
	mutations: {
		setBanner(state, data) {
			if (!data) return
			state.bannerImage = data
			uni.setStorage({
				key: BANNER_IMAGE_KEY,
				data
			})
		},
		clearSearch(state) {
			state.historySearch.splice(0, state.historySearch.length)
			uni.removeStorage({ key: SEARCH_HISTORY_KEY })
		},
		addSearchItem(state, value) {
			const index = state.historySearch.findIndex(item => item.value === value)
			if (index !== -1) {
				state.historySearch.splice(index, 1)
			}
			const item = {
				value,
				time: Date.now(),
			}
			state.historySearch.push(item)
			uni.setStorage({
				key: SEARCH_HISTORY_KEY,
				data: state.historySearch,
			})
		},
		setHasLocation(state, v) {
			state.hasLocation = v
		},
		setOrderData(state, value) {
			state.orderData = value
			uni.setStorage({
				key: 'order_data',
				data: value,
			})
		},
		updateStatusHeight(state) {
			const { statusBarHeight } = uni.getSystemInfoSync()
			state.statusBarHeight = statusBarHeight
			uni.setStorage({
				key: STATUS_HEIGHT_KEY,
				data: statusBarHeight
			})
		},
		setHeight(state, value) {
			state.contentHeight = value
			uni.setStorage({
				key: CONTENT_HEIGHT,
				data: value
			})
		},
		setCategory(state, list) {
			state.categoryList = list
			uni.setStorage({
				key: CATEGORY_LIST_KEY,
				data: list
			})
		},
		logout(state) {
			state.userInfo = {}
			state.token = ''
			uni.clearStorage()
		},
		login(state, v) {
			state.token = v
			uni.setStorage({
				key: TOKEN_KEY,
				data: v
			})
		},
		setUserInfo(state, v) {
			state.userInfo = v
			state.loginSuccess = true
			uni.setStorage({
				key: USERINFO_CACHE_NAME,
				data: v
			})
		},
		addSearch(state, value) {
			const index = state.searchList.findIndex(item => item.label === value.label)
			if (index !== -1) {
				value = state.searchList.splice(index, 1)[0]
			}
			state.searchList.unshift(value)
			uni.setStorage({
				key: 'search_list',
				data: state.searchList
			})
		},

	},
	getters,
	modules: {
		location
	}
})

export default store